package user_private_key

import (
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/repository/mongodb/user_private_key"
	"chain_bridge_service/pkg/errors"
)

type UserPrivateKeyData struct {
	Id              string `bson:"_id,omitempty" json:"id"`
	UserId          string `bson:"userId" json:"userId"`
	MainCoinType    int64  `bson:"mainCoinType" json:"mainCoinType"`                 // udun的id
	FeeAddress      string `bson:"feeAddress,omitempty" json:"feeAddress"`           // 手续费地址（私钥）
	CollectAddress  string `bson:"collectAddress,omitempty" json:"collectAddress"`   // 归集地址
	WithdrawAddress string `bson:"withdrawAddress,omitempty" json:"withdrawAddress"` // 提币地址（私钥）
	ChainName       string `bson:"chainName" json:"chainName"`
}

func (s *service) Create(ctx core.Context, keyData *UserPrivateKeyData) (err error) {
	model := user_private_key.NewModel()

	if keyData.FeeAddress[0:2] == "0x" {
		model.FeeAddress = keyData.FeeAddress[2:]
	} else {
		model.FeeAddress = keyData.FeeAddress
	}
	//if keyData.WithdrawAddress[0:2] == "0x" {
	//	model.WithdrawAddress = keyData.WithdrawAddress[2:]
	//} else {
	//	model.WithdrawAddress = keyData.WithdrawAddress
	//}

	_, err = user_private_key.PrivateToAddress(model.FeeAddress)
	if err != nil {
		return err
	}
	//_, err = user_private_key.PrivateToAddress(model.WithdrawAddress)
	//if err != nil {
	//	return err
	//}

	model.CollectAddress = keyData.CollectAddress
	model.UserId = keyData.UserId
	model.MainCoinType = keyData.MainCoinType
	model.ChainName = keyData.ChainName

	flag, err := model.GetInfoCount(s.db.GetDb())
	if err != nil {
		return err
	}
	if !flag {
		return errors.New("请勿重复添加!")
	}
	err = model.Create(s.db.GetDb())
	return err
}

func (s *service) List(ctx core.Context, userId string, pageIndex uint, pageSize uint) (keyList []user_private_key.UserPrivateKey, err error) {
	model := user_private_key.NewModel()
	model.UserId = userId
	list, err := model.List(s.db.GetDb(), pageIndex, pageSize)
	return list, err
}

func (s *service) Update(ctx core.Context, keyData *UserPrivateKeyData) (err error) {
	model := user_private_key.NewModel()
	model.FeeAddress = keyData.FeeAddress
	model.CollectAddress = keyData.CollectAddress
	//model.WithdrawAddress = keyData.WithdrawAddress
	model.Id = keyData.Id
	err = model.Update(s.db.GetDb())
	return err
}

func (s *service) Count(ctx core.Context, userId string) (count int64, err error) {
	model := user_private_key.NewModel()
	model.UserId = userId
	num, err := model.Count(s.db.GetDb())
	return num, err
}
